package com.example.exception;

import com.example.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GrobleExpectionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器发生异常: ", e);
        return Result.error("服务器发生  异常");
    }

    @ExceptionHandler
    public Result handledDuplicateKeyException(DuplicateKeyException e) {
        log.error("数据库发生重复键异常: ", e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String[] arr = errMsg.split(" ");
        String field = arr[2];
        return Result.error(field + "已存在");
    }

}

